package com.service.business.otc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.service.core.rest.response.CommonPageRep;
import com.service.dao.mapper.OtcOrderDetailMapper;
import com.service.dao.model.Member;
import com.service.dao.model.OtcOrderDetail;
import com.service.business.member.service.MemberService;
import com.service.business.otc.controller.rep.OtcOrderDetailPageRep;
import com.service.business.otc.controller.req.OtcOrderDetailPageReq;
import com.service.business.otc.service.OtcOrderDetailService;
import com.service.utility.modelmapper.ModelMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service("hmOtcOrderDetailService")
public class OtcOrderDetailServiceImpl extends ServiceImpl<OtcOrderDetailMapper, OtcOrderDetail> implements OtcOrderDetailService {

    @Autowired
    private MemberService memberService;

    @Override
    public CommonPageRep<OtcOrderDetailPageRep> pageUserOrderDetail(OtcOrderDetailPageReq pageRequest) {

        Page<OtcOrderDetail> page = PageHelper.startPage(pageRequest.getPageNo(), pageRequest.getPageSize());
        baseMapper.selectList(new QueryWrapper<OtcOrderDetail>().lambda()
                .eq(OtcOrderDetail::getMemberId, pageRequest.getMemberId())
                .eq(OtcOrderDetail::getDetailType, pageRequest.getType())
                .orderByDesc(OtcOrderDetail::getId));

        List<OtcOrderDetailPageRep> list = page.getResult().stream().map(item -> {
            OtcOrderDetailPageRep data = ModelMapperUtil.getStrictModelMapper().map(item, OtcOrderDetailPageRep.class);
            buildMemberInfo(item.getSourceMemberId(), data);
            return data;
        }).collect(Collectors.toList());

        return CommonPageRep.buildResultRep(page, list);
    }

    private void buildMemberInfo(Integer memberId, OtcOrderDetailPageRep otcOrderPageRep) {
        Member member = memberService.getById(memberId);
        otcOrderPageRep.setMemberName(member.getUserName());
        otcOrderPageRep.setMemberHeadImg(member.getImgHead());
        otcOrderPageRep.setDealOrderNum(this.countDealOrderNum(memberId));
    }

    @Override
    public Integer countDealOrderNum(Integer memberId) {
        return baseMapper.selectCount(new QueryWrapper<OtcOrderDetail>().lambda()
                .eq(OtcOrderDetail::getSourceMemberId, memberId)
                .or().eq(OtcOrderDetail::getMemberId, memberId));
    }
}
